package cn.xorange.commons.system.service.System.impl;

import cn.xorange.commons.core.annotation.DataScope;
import cn.xorange.commons.core.basic.service.BaseService;
import cn.xorange.commons.data.constants.DataConstants;
import cn.xorange.commons.security.entity.SecurityUser;
import cn.xorange.commons.security.utils.SecurityUtils;
import cn.xorange.commons.system.entity.system.SysOrg;
import cn.xorange.commons.system.mapper.system.SysOrgMapper;
import cn.xorange.commons.system.service.System.ISysOrgService;
import cn.xorange.commons.utils.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author : yangjian
 * date : 2022/2/25
 */
@Service
public class SysOrgServiceImpl extends BaseService<SysOrg, SysOrgMapper> implements ISysOrgService {


    /**
     * 可管理组织架构 管理角色、角色管理 菜单赋权使用
     * @return List
     */
    @Override
    public List<SysOrg> getManageOrgList() {
        SysOrg sysOrg = new SysOrg();
        sysOrg.setTenantId(SecurityUtils.getTenantId());
        Long userId = SecurityUtils.getUserId();
        Map<String, String> scope = new HashMap<>();
        boolean isAdmin = SecurityUtils.userIsAdmin();

        if(!isAdmin){
            scope = mapper.selectDataScope(userId);
            for(String k : scope.keySet()){
                if(DataConstants.DATA_SCOPE_ALL.equals(k)){
                    isAdmin = true;
                    break;
                }
            }
        }
        if(!isAdmin){
            StringBuilder sb = new StringBuilder();
            SecurityUser user = SecurityUtils.getUser();
            for(String k : scope.keySet()){
                if(DataConstants.DATA_SCOPE_CUSTOM.equals(k)){
                    sb.append(StringUtils.format(" or find_in_set(org_id, {})",scope.get(k)));
                }else if(DataConstants.DATA_SCOPE_OUR_ORG.equals(k)){
                    sb.append(StringUtils.format(" or org_id = {} ", user.getOrgId() ));
                }else if(DataConstants.DATA_SCOPE_OUR_ORG_LINK.equals(k)){
                    String ids = StringUtils.format("{},{}", user.getOrgId() ,user.getTreeNode());
                    sb.append(StringUtils.format(" or find_in_set(org_id, {})", ids));
                }else {
                    sb.append("or org_id = 0");
                }
            }
            if(sb.length()>0){
                sysOrg.setParams("dataScope", sb.substring(4));
            }else {
                sysOrg.setParams("dataScope", " and org_id = 0");
            }
        }

        return mapper.selectManageOrgList(sysOrg);
    }

    @Override
    @DataScope(orgAlias = "o")
    public List<SysOrg> getList(SysOrg sysOrg) {
        Long tenantId = SecurityUtils.getTenantId();
        sysOrg.setTenantId(tenantId);
        return mapper.selectList(sysOrg);
    }

    @Override
    public int checkOrgNameUnique(SysOrg org) {
        return mapper.checkOrgNameUnique(org);
    }


    /**
     * 根据ID查询所有子部门（正常状态）
     *
     * @param deptId 部门ID
     * @return 子部门数
     */
    @Override
    public int selectNormalChildrenDeptById(Long deptId) {
        return mapper.selectNormalChildrenDeptById(deptId);
    }

    /**
     * 是否存在子节点
     * @param deptId 部门ID
     * @return 结果
     */
    @Override
    public boolean hasChildByDeptId(Long deptId) {
        int result = mapper.hasChildByDeptId(deptId);
        return result > 0;
    }

    /**
     * 查询部门是否存在用户
     * @param deptId 部门ID
     * @return 结果 true 存在 false 不存在
     */
    @Override
    public boolean checkDeptExistUser(Long deptId) {
        int result = mapper.checkDeptExistUser(deptId);
        return result > 0;
    }

    /**
     * 修改该部门的父级部门状态
     *
     * @param dept 当前部门
     */
    public void updateParentDeptStatusNormal(SysOrg dept) {
        String ancestors = dept.getTreeNode();
        Long[] deptIds = StringUtils.toLongArray(ancestors,",");
        mapper.updateDeptStatusNormal(deptIds);
    }


}
